import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import {
  Card,
  Button,
  Form,
  Input,
  Modal,
  Descriptions,
  Steps,
  Divider,
  Drawer,
  Timeline,
  Spin,
  Cascader,
  message,
} from 'antd';
import MyPageTable from '@/components/MyPageTable';
import AntTable from '@/components/AntTable';
import { onTableData, getParam } from '@/utils/utils.js';
import CreditDetail from './creditDetail';
const { TextArea } = Input;
const { Step } = Steps;
import CustomCard from '@/components/CustomCard';
import { optionsdata } from './data.js';
import axios from 'axios';
function getToken() {
  const token = localStorage.getItem('business-token');
  return token;
}
@connect(({ order, loading, RentRenewalLoading }) => ({
  ...order,
  loading: loading.effects['order/queryOpeUserOrderDetail'],
  RentRenewalLoading: loading.effects['order/userOrdersPurchase'],
}))
@Form.create()
export default class Details extends Component {
  state = {
    drawerVisible: false,
    drawerData: [],
    visible: false,
    visibles: false,
    settlement: null,
    xcurrent: 1,
    scurrent: 1,
    titles: '',
    subLists: [],
    creditInfo: {}, //信用详情
    userOrdersPurchase: {},
    CashesDto: [],
    businessRemarkDtoList: [],
    businessRemarkDtoTotal: 1,
    comprehensiveSuggest: '',
  };
  componentDidMount() {
    this.onRentRenewalDetail();
    this.onQueryOrderRemark(1, 3, '01');
    axios(`/hzsx/business/order/queryOrderRemark`, {
      method: 'post',
      headers: { token: getToken() },
      data: {
        orderId: getParam('id'),
        pageNumber: 1,
        pageSize: 10,
        source: '02',
      },
    }).then(res => {
      this.setState({
        businessRemarkDtoList: res.data.data.records,
        businessRemarkDtoTotal: res.data.data.total,
      });
    });
  }
  onRentRenewalDetail = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/userOrdersPurchase',
      payload: {
        orderId: getParam('id'),
      },
      callback: res => {
        this.setState({
          userOrdersPurchase: res.data,
          CashesDto: [
            {
              totalAmount: res.data.totalAmount,
              shopCouponReduction: res.data.shopCouponReduction,
              platformCouponReduction: res.data.platformCouponReduction,
              freightAmount: res.data.freightAmount,
              hbPeriodNum: res.data.hbPeriodNum,
            },
          ],
        });
      },
    });
  };
  onQueryOrderRemark = (pageNumber, pageSize, source) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/queryOrderRemark',
      payload: {
        orderId: getParam('id'),
        pageNumber,
        pageSize,
        source,
      },
    });
  };
  //新建备注翻页
  onPage = e => {
    this.setState(
      {
        xcurrent: e.current,
      },
      () => {
        this.onQueryOrderRemark(e.current, 3, '01');
      },
    );
  };
  //商机备注翻页
  onPageBusiness = e => {
    this.setState(
      {
        scurrent: e.current,
      },
      () => {
        this.onQueryOrderRemark(e.current, 3, '02');
      },
    );
  };
  //物流信息
  onClose = () => {
    this.setState({
      drawerVisible: false,
    });
  };
  //查看物流
  onLogistics = (e, i) => {
    this.setState(
      {
        drawerVisible: true,
        drawerTitle: e,
      },
      () => {
        this.onQueryExpressInfo(i);
      },
    );
  };
  handleOk = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { dispatch, userOrderInfoDto } = this.props;

        if (this.state.titles === '备注') {
          if (getParam('RentRenewal')) {
            dispatch({
              type: 'order/telephoneAuditOrder',
              payload: {
                orderId: getParam('id'),
                remark: values.beizhu,
                orderType: '01',
              },
              callback: res => {
                this.onQueryOrderRemark(1, 3, '01');
                this.setState({
                  visible: false,
                });
              },
            });
          } else {
            dispatch({
              type: 'order/orderRemark',
              payload: {
                orderId: getParam('id'),
                remark: values.beizhu,
                orderType: '01',
              },
              callback: res => {
                axios(`/hzsx/business/order/queryOrderRemark`, {
                  method: 'post',
                  headers: { token: getToken() },
                  data: {
                    orderId: getParam('id'),
                    pageNumber: 1,
                    pageSize: 10,
                    source: '02',
                  },
                }).then(res => {
                  this.setState({
                    businessRemarkDtoList: res.data.data.records,
                    businessRemarkDtoTotal: res.data.data.total,
                    visible: false,
                  });
                });
                // this.setState({
                //   visible: false,
                // });
              },
            });
          }
        } else {
          dispatch({
            type: 'order/opeOrderAddressModify',
            payload: {
              realName: values.realName,
              street: values.street,
              telephone: values.telephone,
              province: values && values.city && values.city[0],
              city: values && values.city && values.city[1],
              area: values && values.city && values.city[2],
              orderId: getParam('id'),
            },
            callback: res => {
              this.onRentRenewalDetail();
              this.setState({
                visible: false,
              });
            },
          });
        }
      }
    });
  };
  onQueryExpressInfo = i => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/expressInfo',
      payload: {
        orderId: i,
      },
    });
  };
  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };
  handleCancels = e => {
    this.setState({
      visibles: false,
    });
  };
  showModal = e => {
    this.setState({
      visible: true,
      titles: e,
    });
  };
  onXY = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/contractReport',
      payload: {
        orderId: getParam('id'),
      },
    });
  };
  viewCredit = id => {
    this.props.dispatch({
      type: 'order/getCredit',
      payload: {
        uid: id,
      },
      callback: res => {
        if (res.responseType === 'SUCCESS') {
          this.setState(
            {
              visibles: res.data ? true : false,
              creditInfo: res.data,
              comprehensiveSuggest: res.data.comprehensiveSuggest || '',
            },
            () => {},
          );
        } else {
          message.error(res.data.msg);
        }
      },
    });
  };
  render() {
    const {
      userOrderInfoDto,
      shopInfoDto,
      orderAddressDto,
      receiptExpressInfo,
      giveBackExpressInfo,
      OrderRemarkDataList,
      OrderRemarkDataTotal,

      productInfo,
      userOrderCashesDto,
      orderByStagesDtoList,
      orderBuyOutDto,
      wlList,
    } = this.props;
    const {
      drawerVisible,
      drawerData,
      settlement,
      visibles,
      userOrdersPurchase,
      businessRemarkDtoList,
      businessRemarkDtoTotal,
    } = this.state;

    let detaState = {
      WAITING_FOR_PAY: 0,
      CANCEL: 3,
      WAITING_FOR_DELIVERY: 1,
      WAITING_RECEIVE: 2,
      FINISH: 3,
    };
    let detailsStute = {
      '01': '待支付',
      '02': '支付中',
      '03': '已支付申请关单',
      '04': '待发货',
      '05': '待确认收货',
      '06': '租用中',
      '07': '待结算',
      '08': '结算待支付',
      '09': '订单完成',
      '10': '交易关闭',
    };
    let columnsByStagesStute = {
      '1': '待支付',
      '2': '已支付',
      '3': '逾期已支付',
      '4': '逾期待支付',
      '5': '已取消',
      '6': '已结算',
      '7': '已退款',
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    //平台备注
    const columns = [
      {
        title: '备注人姓名',
        dataIndex: 'userName',
      },
      {
        title: '备注时间',
        dataIndex: 'createTime',
      },
      {
        title: '备注内容',
        dataIndex: 'remark',
      },
    ];
    //商家备注
    const columnsBusiness = [
      {
        title: '备注人姓名',
        dataIndex: 'userName',
      },
      {
        title: '备注时间',
        dataIndex: 'createTime',
      },
      {
        title: '备注内容',
        dataIndex: 'remark',
      },
    ];
    //商品信息
    const columnsInformation = [
      {
        title: '商品图片',
        dataIndex: 'src',
        render: src => {
          return (
            <img
              src={src}
              style={{
                width: 116,
                height: 62,
              }}
            />
          );
        },
      },
      {
        title: '商品名称',
        dataIndex: 'productName',
      },
      {
        title: '商品编号',
        dataIndex: 'productId',
      },
      {
        title: '规格颜色',
        dataIndex: 'specAll',
        render: specAll => {
          return (
            <span>
              {specAll && specAll[0] && specAll[0].platformSpecValue}/
              {specAll && specAll[0] && specAll[1].platformSpecValue}
            </span>
          );
        },
      },
      {
        title: '数量',
        render: e => 1,
      },
      // {
      //   title: '是否可分期',
      //   dataIndex: 'isSupportStage',
      //   align: 'center',
      //   render: text => (text === 1 ? '分期' : '不分期'),
      // },
      {
        title: '运费',
        render: e => '到付',
      },
    ];

    //账单信息
    const columnsBill = [
      {
        title: '总金额',
        dataIndex: 'totalAmount',
        align: 'center',
        key: 'totalAmount',
      },
      {
        title: '平台优惠',
        dataIndex: 'platformCouponReduction',
        align: 'center',
        key: 'platformCouponReduction',
      },
      {
        title: '店铺优惠',
        dataIndex: 'shopCouponReduction',
        align: 'center',
        key: 'shopCouponReduction',
      },
      {
        title: '分期信息',
        dataIndex: 'hbPeriodNum',
        align: 'center',
        key: 'hbPeriodNum',
      },
      {
        title: '运费',
        dataIndex: 'freightAmount',
        align: 'center',
        key: 'freightAmount',
      },
    ];

    //分期
    const columnsByStages = [
      {
        title: '总期数',
        dataIndex: 'totalPeriods',
      },
      {
        title: '当前期数',
        dataIndex: 'currentPeriods',
      },
      {
        title: '租金',
        dataIndex: 'currentPeriodsRent',
      },
      {
        title: '状态',
        dataIndex: 'status',
        render: status => <span>{columnsByStagesStute[status]}</span>,
      },
      {
        title: '支付时间',
        dataIndex: 'repaymentDate',
      },
      {
        title: '账单到期时间',
        dataIndex: 'statementDate',
      },
    ];
    //买断
    const columnsBuyOut = [
      {
        title: '创建时间',
        dataIndex: 'createTime',
      },
      {
        title: '订单编号',
        dataIndex: 'buyOutOrderId',
      },
      {
        title: '商品名称',
        dataIndex: 'productName',
      },
      {
        title: '销售价',
        dataIndex: 'realSalePrice',
      },
      {
        title: '已付租金',
        dataIndex: 'paidRent',
      },
      {
        title: '买断尾款',
        dataIndex: 'endFund',
      },
    ];
    //结算
    const columnsSettlement = [
      {
        title: '结算单状态',
        dataIndex: 'scenario_type',
      },
      {
        title: '结算类型',
        dataIndex: 'scenario_name',
      },
      {
        title: '结算金额',
        dataIndex: 'description',
      },
      {
        title: '原因',
        dataIndex: 'description1',
      },
    ];
    const paginationProps = {
      current: 1,
      pageSize: 1000,
      total: 1,
    };
    let detailsStutes = {
      WAITING_FOR_PAY: '待支付',
      CANCEL: '已取消',
      WAITING_FOR_DELIVERY: '待发货',
      WAITING_RECEIVE: '待收货',
      FINISH: '已完成',
    };
    const { getFieldDecorator } = this.props.form;
    return (
      <PageHeaderWrapper>
        <Spin spinning={this.props.RentRenewalLoading}>
          <Card title={<CustomCard title="订单进度" />} bordered={false}>
            <Steps
              progressDot={document.body.clientWidth < 1025 ? false : true}
              current={detaState[userOrdersPurchase && userOrdersPurchase.state]}
            >
              <Step title="买家下单" />
              <Step title="买家付款" />
              <Step title="商家发货" />
              <Step title="买家确认收货" />
              <Step title="订单完成" />
            </Steps>
          </Card>
          <Card bordered={false} style={{ marginTop: 20 }}>
            <Descriptions title={<CustomCard title="订单信息" />}>
              <Descriptions.Item label="下单人姓名">
                {userOrdersPurchase && userOrdersPurchase.userName}
              </Descriptions.Item>
              <Descriptions.Item label="下单人手机号">
                {userOrdersPurchase && userOrdersPurchase.telephone}
              </Descriptions.Item>
              <Descriptions.Item label="下单时间">
                {userOrdersPurchase && userOrdersPurchase.createTime}
              </Descriptions.Item>
              <Descriptions.Item label="订单状态">
                {detailsStutes[userOrdersPurchase && userOrdersPurchase.state]}
              </Descriptions.Item>
            </Descriptions>
            <Divider />
            <CustomCard title="平台备注" style={{ marginBottom: 10 }} />

            <MyPageTable
              onPage={this.onPage}
              paginationProps={{
                current: this.state.xcurrent,
                pageSize: 3,
                total: OrderRemarkDataTotal,
              }}
              dataSource={onTableData(OrderRemarkDataList)}
              columns={columns}
            />
            <Divider />
            {businessRemarkDtoList ? (
              <>
                <CustomCard title="商家备注" style={{ marginBottom: 20 }} />
                <Button
                  type="primary"
                  style={{ margin: '20px 0' }}
                  onClick={() => this.showModal('备注')}
                >
                  + 新建备注
                </Button>
                <MyPageTable
                  onPage={this.onPageBusiness}
                  paginationProps={{
                    current: this.state.scurrent,
                    pageSize: 3,
                    total: businessRemarkDtoTotal,
                  }}
                  dataSource={onTableData(businessRemarkDtoList)}
                  columns={columnsBusiness}
                />
                <Divider />
              </>
            ) : null}

            <Descriptions title={<CustomCard title="商家信息" />}>
              <Descriptions.Item label="商家名称">
                {userOrdersPurchase && userOrdersPurchase.shopName}
              </Descriptions.Item>
              <Descriptions.Item label="商家电话" span={2}>
                {userOrdersPurchase && userOrdersPurchase.telephone}
              </Descriptions.Item>
            </Descriptions>
            <Divider />

            <Descriptions
              title={
                <>
                  <CustomCard title="收货人信息" />
                  {/* {userOrderInfoDto && userOrderInfoDto.status === '04' ? (
                        <Button onClick={() => this.showModal('修改地址')}>修改地址</Button>
                      ) : null}
                      {userOrderInfoDto && userOrderInfoDto.status === '01' ? (
                        <Button onClick={() => this.showModal('修改地址')}>修改地址</Button>
                      ) : null}
                      {userOrderInfoDto && userOrderInfoDto.status === '02' ? (
                        <Button onClick={() => this.showModal('修改地址')}>修改地址</Button>
                      ) : null}
                      {userOrderInfoDto && userOrderInfoDto.status === '03' ? (
                        <Button onClick={() => this.showModal('修改地址')}>修改地址</Button>
                      ) : null} */}
                </>
              }
            >
              <Descriptions.Item label="收货人姓名">
                {userOrdersPurchase &&
                  userOrdersPurchase.address &&
                  userOrdersPurchase.address.realname}
              </Descriptions.Item>
              <Descriptions.Item label="收货人手机号">
                {userOrdersPurchase &&
                  userOrdersPurchase.address &&
                  userOrdersPurchase.address.telephone}
              </Descriptions.Item>
              <Descriptions.Item label="收货人地址">
                {userOrdersPurchase &&
                  userOrdersPurchase.address &&
                  userOrdersPurchase.address.street}
              </Descriptions.Item>
              <Descriptions.Item label="用户备注">
                {userOrdersPurchase && userOrdersPurchase.remark}
              </Descriptions.Item>
            </Descriptions>
            <Divider />

            {userOrdersPurchase && userOrdersPurchase.expressInfo ? (
              <>
                <Descriptions title={<CustomCard title="发货物流信息" />}>
                  <Descriptions.Item label="发货物流公司">
                    {userOrdersPurchase.expressInfo.expressCompany}
                  </Descriptions.Item>
                  <Descriptions.Item label="发货物流单号">
                    {userOrdersPurchase.expressInfo.expressNo}
                  </Descriptions.Item>
                  <Descriptions.Item label="发货时间">
                    {userOrdersPurchase.expressInfo.deliveryTime}
                  </Descriptions.Item>
                </Descriptions>
                <Button onClick={() => this.onLogistics('发货物流信息', getParam('id'))}>
                  查看物流
                </Button>
                <Divider />
              </>
            ) : null}
          </Card>
          <Card bordered={false} style={{ margin: '30px 0' }}>
            <CustomCard title="商品信息" style={{ marginBottom: 20 }} />
            <AntTable
              columns={columnsInformation}
              dataSource={onTableData(userOrdersPurchase && [userOrdersPurchase.productInfo])}
              paginationProps={paginationProps}
            />
            <CustomCard title="账单信息" style={{ marginBottom: 20 }} />
            <AntTable
              columns={columnsBill}
              dataSource={onTableData(this.state.CashesDto)}
              paginationProps={paginationProps}
            />
          </Card>
        </Spin>
        <Drawer
          width={420}
          title={this.state.drawerTitle || '发货物流信息'}
          placement="right"
          onClose={this.onClose}
          visible={drawerVisible}
        >
          <Timeline>
            {wlList.map((item, idx) => {
              let color = 'blue';
              if (idx === 0) {
                color = 'green';
              }
              return (
                <Timeline.Item
                  style={{ color: idx !== 0 ? '#aaa' : '#333' }}
                  key={idx}
                  color={color}
                >
                  <p>{item.remark}</p>
                  <p>{item.datetime}</p>
                </Timeline.Item>
              );
            })}
          </Timeline>
        </Drawer>
        <Modal
          title={this.state.titles}
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          {this.state.titles === '备注' ? (
            <Form>
              <Form.Item label="备注内容" {...formItemLayout}>
                {getFieldDecorator('beizhu', {
                  rules: [{ required: true, message: '请输入备注' }],
                })(<TextArea placeholder="请输入" />)}
              </Form.Item>
            </Form>
          ) : (
            <Form>
              <Form.Item label="所在城市" {...formItemLayout}>
                {getFieldDecorator('city', {
                  rules: [
                    {
                      required: true,
                      message: '请输入备注',
                    },
                  ],
                  initialValue: [
                    orderAddressDto &&
                      orderAddressDto.province &&
                      orderAddressDto.province.toString(),
                    orderAddressDto && orderAddressDto.city && orderAddressDto.city.toString(),
                    orderAddressDto && orderAddressDto.area && orderAddressDto.area.toString(),
                  ],
                })(
                  <Cascader
                    options={optionsdata}
                    fieldNames={{ label: 'name', value: 'value', children: 'subList' }}
                  />,
                )}
              </Form.Item>
              <Form.Item label="收货人姓名" {...formItemLayout}>
                {getFieldDecorator('realName', {
                  rules: [{ required: true, message: '请输入备注' }],
                  initialValue: orderAddressDto && orderAddressDto.realname,
                })(<Input placeholder="请输入" />)}
              </Form.Item>
              <Form.Item label="收货人手机号" {...formItemLayout}>
                {getFieldDecorator('telephone', {
                  rules: [{ required: true, message: '请输入备注' }],
                  initialValue: orderAddressDto && orderAddressDto.telephone,
                })(<Input placeholder="请输入" />)}
              </Form.Item>
              <Form.Item label="详细地址" {...formItemLayout}>
                {getFieldDecorator('street', {
                  rules: [{ required: true, message: '请输入备注' }],
                  initialValue: orderAddressDto && orderAddressDto.street,
                })(<TextArea placeholder="请输入" />)}
              </Form.Item>
            </Form>
          )}
        </Modal>
        <Modal
          title={<p style={{ textAlign: 'center', marginBottom: 0 }}>风险分</p>}
          visible={visibles}
          width="1200px"
          footer={null}
          onCancel={this.handleCancels}
        >
          <CreditDetail
            userOrders={userOrderInfoDto}
            creditInfo={this.state.creditInfo}
            userOrderInfoDto={userOrderInfoDto}
            orderAddressDto={orderAddressDto}
            productInfo={productInfo}
            userOrderCashesDto={userOrderCashesDto}
            comprehensiveSuggest={this.state.comprehensiveSuggest}
          ></CreditDetail>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
